package edu.software.PBL_Management_System.demand.controller;

import edu.software.PBL_Management_System.demand.service.DemandService;
import edu.software.PBL_Management_System.entity.Demand;
import edu.software.PBL_Management_System.entity.User;
import edu.software.PBL_Management_System.util.DemandUtil;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping("/api/demands")
public class DemandController{

    @Resource
    private DemandService demandService;

    @Resource
    private DemandUtil demandUtil;

    @PostMapping
    public ResponseEntity<Demand> createDemand(@RequestBody Demand demand, @RequestParam Long creatorId) {
        try {
            User creator = demandUtil.getUserById(creatorId);
            demand.setCreator(creator);
            demand.setCreatedTime(LocalDateTime.now());
            demand.setUpdatedTime(LocalDateTime.now());

            // 验证mindMapData是否为有效的JSON
            if (demand.getMindMapData() != null && !demand.getMindMapData().isEmpty()) {
                try {
                    // 尝试解析JSON，确保数据有效
                    new ObjectMapper().readTree(demand.getMindMapData());
                } catch (JsonProcessingException e) {
                    return ResponseEntity.badRequest().build();
                }
            }

            return ResponseEntity.ok(demandService.createDemand(demand));
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<Demand> updateDemand(@PathVariable Long id, @RequestBody Demand demand) {
        demand.setId(id);
        return ResponseEntity.ok(demandService.updateDemand(demand));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Demand> getDemand(@PathVariable Long id) {
        return ResponseEntity.ok(demandService.getDemandById(id));
    }

    @GetMapping("/creator/{creatorId}")
    public ResponseEntity<List<Demand>> getDemandsByCreator(@PathVariable Long creatorId) {
        User creator = demandUtil.getUserById(creatorId);
        return ResponseEntity.ok(demandService.getDemandsByCreator(creator));
    }

    @GetMapping("/creator/{creatorId}/paged")
    public ResponseEntity<Page<Demand>> getDemandsByCreatorPaged(
            @PathVariable Long creatorId,
            Pageable pageable) {
        User creator = demandUtil.getUserById(creatorId);
        return ResponseEntity.ok(demandService.getDemandsByCreator(creator, pageable));
    }

    @GetMapping("/status/{status}")
    public ResponseEntity<List<Demand>> getDemandsByStatus(
            @PathVariable Demand.DemandStatus status) {
        return ResponseEntity.ok(demandService.getDemandsByStatus(status));
    }

    @GetMapping("/parent/{parentId}")
    public ResponseEntity<List<Demand>> getSubDemands(@PathVariable Long parentId) {
        return ResponseEntity.ok(demandService.getSubDemands(parentId));
    }

    @GetMapping("/main")
    public ResponseEntity<Page<Demand>> getMainDemands(
            Pageable pageable,
            @RequestParam(required = false) Long excludeUserId) {
        return ResponseEntity.ok(demandService.getMainDemands(pageable, excludeUserId));
    }

    @GetMapping("/search")
    public ResponseEntity<List<Demand>> searchDemands(@RequestParam String title) {
        return ResponseEntity.ok(demandService.searchDemandsByTitle(title));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDemand(@PathVariable Long id) {
        demandService.deleteDemand(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/{id}/publish")
    public ResponseEntity<Demand> publishDemand(@PathVariable Long id) {
        return ResponseEntity.ok(demandService.publishDemand(id));
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<Demand> updateDemandStatus(
            @PathVariable Long id,
            @RequestParam Demand.DemandStatus status) {
        return ResponseEntity.ok(demandService.updateDemandStatus(id, status));
    }

    @GetMapping("/creator/{creatorId}/status/{status}")
    public ResponseEntity<List<Demand>> getDemandsByCreatorAndStatus(
            @PathVariable Long creatorId,
            @PathVariable Demand.DemandStatus status) {
        User creator = demandUtil.getUserById(creatorId);
        return ResponseEntity.ok(demandService.getDemandsByCreatorAndStatus(creator, status));
    }

    /**
     * 获取需求详细信息
     */
    @GetMapping("/{id}/details")
    public ResponseEntity<Map<String, Object>> getDemandDetails(@PathVariable Long id) {
        return ResponseEntity.ok(demandService.getDemandDetailsById(id));
    }

    /**
     * 获取用户的需求基本信息列表
     */
    @GetMapping("/creator/{creatorId}/list")
    public ResponseEntity<List<Map<String, Object>>> getDemandsList(@PathVariable Long creatorId) {
        try {
            // 使用 DemandUtil 获取用户
            User creator = demandUtil.getUserById(creatorId);
            if (creator == null) {
                return ResponseEntity.notFound().build();
            }
            // 使用新的服务方法获取顶级需求
            List<Map<String, Object>> demands = demandService.getTopLevelDemandBasicListByCreator(creator);
            return ResponseEntity.ok(demands);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 按状态获取用户的需求基本信息列表
     */
    @GetMapping("/creator/{creatorId}/status/{status}/list")
    public ResponseEntity<List<Map<String, Object>>> getDemandsByStatusList(
            @PathVariable Long creatorId,
            @PathVariable Demand.DemandStatus status) {
        User creator = demandUtil.getUserById(creatorId);
        return ResponseEntity.ok(demandService.getDemandBasicListByCreatorAndStatus(creator, status));
    }

    @PostMapping("/sub-demand")
    public ResponseEntity<Map<String, Object>> createEmptySubDemand(
            @RequestParam Long parentId,
            @RequestParam Long creatorId) {
        User creator = demandUtil.getUserById(creatorId);
        return ResponseEntity.ok(demandService.createEmptySubDemand(parentId, creator));
    }


    /**
     * 获取已评论的需求列表
     */
    @GetMapping("/commented")
    public ResponseEntity<List<Demand>> getCommentedDemands() {
        try {
            List<Demand> demands = demandService.getCommentedDemands();
            return ResponseEntity.ok(demands);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}/mindmap")
    public ResponseEntity<Map<String, Object>> getDemandMindmap(@PathVariable Long id) {
        Map<String, Object> mindmapData = demandService.getDemandMindmapData(id);
        return ResponseEntity.ok(mindmapData);
    }

    // 新增：获取用户的顶级需求列表
    @GetMapping("/creator/{creatorId}/top-level")
    public ResponseEntity<List<Map<String, Object>>> getTopLevelDemands(@PathVariable Long creatorId) {
        try {
            User creator = demandUtil.getUserById(creatorId);
            if (creator == null) {
                return ResponseEntity.notFound().build();
            }
            // 使用优化后的repository方法
            List<Map<String, Object>> demands = demandService.getTopLevelDemandBasicListByCreator(creator);
            return ResponseEntity.ok(demands);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
